<template>
	<view class="balloutTime" style="font-family: NotoSansSC-Regular">
		<loading :showLoaded.sync="showLoaded"></loading>
		<navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
		<view class="title__bar" v-if="b_lists.length && isShowData">
			<view style="display: flex; align-items: center; height: 72rpx">
				<img src="https://100000063-1252208446.file.myqcloud.com/images/icon@2x (4).png" alt="" style="
            width: 32rpx;
            height: 32rpx;
            margin-right: 24rpx;
            margin-top: 5rpx;
          " />
				<text style="color: #fff; font-weight: 400; font-size: 24rpx">
					{{ "恭喜您获得麦卡伦" + getNavTitle() + "商品购买权限" }}</text>
				<text></text>
			</view>
			<view class="icon" @click="ontoHistory">
				<label class="macallan-icon mcl-youjiantou" style="font-weight: 600; color: #fff"></label>
			</view>
		</view>
		<!-- 1行2列 -->
		<view class="goodsList">
			<view :style="{ paddingBottom: (isIpx ? 75 : 55) + 'px' }">
				<view v-if="utoolsData && utoolsClassGoodsLists">
					<utools-parse id="utools-parse" page="category" @triggerComponent="onTriggerComponent" :utools-data="utoolsData" @onAddCart="onAddCart">
					</utools-parse>
				</view>
				<!-- 登记历史滑动 -->
				<view v-if="this.historyList.length">
					<swiperContent :historyList="historyList" :historyTotal="historyTotal" :userOrderLists="userOrderLists"
						@onGetBalloutHistory="getBalloutHistory" />
				</view>
			</view>
		</view>
		<view class="ios_safe_zone" v-if="isIos">
			<view class="ios_safe_zone_line"></view>
		</view>
		<cart-toast v-if="showCartMsg" :cartMessage="cartMessage" :cartStatus="cartStatus"></cart-toast>

		<!-- 活动规则弹框 -->
		<view class="mask-box-2" v-if="isActivityRule" @click.stop="isActivityRule = false" @touchmove.stop.prevent
			catchtouchmove="true">
			<view class="params-padding-box-3" @click.stop="stopClick">
				<image style="width: 654rpx; height: auto" mode="widthFix" :src="ruleBoxData.title" alt="" />
				<scroll-view style="height: 280rpx; width: 100%" scroll-y="true">
					<view style="
              display: flex;
              flex-direction: column;
              justify-content: flex-start;
              align-items: center;
              padding: 0;
              margin: 0;
              font-size: 0;
            ">
						<block v-for="(img, i) in ruleBoxData.list" :key="i">
							<image style="width: 100%; height: auto" :src="img" mode="widthFix"></image>
						</block>
					</view>
				</scroll-view>
				<view @click.stop="isActivityRule = false" style="
            position: absolute;
            top: 15rpx;
            right: 14rpx;
            width: 90rpx;
            height: 90rpx;
          "></view>
			</view>
		</view>
				<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
	</view>
</template>
<script module="filterChecked" lang="wxs" src="../../utils/filter.wxs"></script>
<script>
	import api from "@/api/api";
	import tip from "@/utils/tip";
	import util from "@/utils/util.js";
	import NavBar from "@/components/common/navbar";
	import loading from "@/components/common/loading";
	import CartToast from "@/components/common/cartToast.vue";
	import SwiperContent from "./components/swiperContent.vue";
	import {
		SYSTEM_INFO,
		MERCHANT_INFO,
		CUSTOMER_INFO,
		USER_INFO,
		CART_KEY,
		USER_SPECICAL_INFO,
	} from "@/utils/constant";
	export default {
		components: {
			navBar: NavBar,
			loading: loading,
			CartToast: CartToast,
			SwiperContent: SwiperContent,
		},
		data() {
			return {
				id: "",
				afterPage: "",
				currentPage: 1,
				pageSize: 50,
				pageTotal: 0,
				cmsImageSrc: "",
				preview: false,
				list: [],
				hasMore: 0,
				nowPages: "",
				isShowCustomNavBar: true,
				// 组件所需的参数
				navbarData: {
					showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
					navbarTitle: "", //导航栏 中间的标题
					isTopFixed: false,
					newLogo: uni.getStorageInfoSync("storeLogo"),
					hideHome: true,
				},
				showLoaded: true,
				utoolsClassGoodsLists: [],
				utoolsData: null,
				navName: null,
				showCartMsg: false,
				cartMessage: "",
				cartStatus: false,
				basicsTag: null,
				isBasicsTag: true,
				isIos: false,
				camelCoseUtoolsList: [],
				historyListDatils: [],
				ballotGoodsLists: [],
				ballotGoodsHistoryLists: [],
				historyList: [],
				historyTotal: 0,
				is_balloutHistory: false, //抽签购历史
				navBarHeight: 0,
				navWinAPrizeList: [], //中奖列表
				b_lists: [], //中奖列表
				isShowData: false, //用户第一次进来展示
				isActivityRule: false, //细则弹窗
				ruleBoxData: {
					title: "https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/activity/Pop-ups.png",
					list: [
						'https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/activity/ballot-tip/Pop-ups@2x_01.png',
						'https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/activity/ballot-tip/Pop-ups@2x_02.png',
						'https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/activity/ballot-tip/Pop-ups@2x_03.png',
						'https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/activity/ballot-tip/Pop-ups@2x_04.png',
						'https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/activity/ballot-tip/Pop-ups@2x_05.png',
					],
				},
				userOrderLists: [], // 微信组件使用
				shareImage: "",
				shareTitle: "",
				pagePath: "",
				pageQuery: "",
			};
		},
		computed: {},
		async onLoad(options = {}) {
			try {
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
				await this.init();
				this.countNavHeight();
				await this.getNavbarTitle();
				await this.getBalloutHistory();
				this.toID(options);
				this.getPageShareData(options);
				setTimeout(() => {
					this.showLoaded = false;
				}, 400);
				this.$commonSensors.lithaTrack.crTrack("PLPView", {
					tab_name: "不凡甄选",
				});
			} catch (e) {

			}
		},
		async onShow() {
			this.userOrderLists = await this.getOrder();
			if (this.ballotGoodsLists && this.ballotGoodsLists.length) {
				this.showLoaded = true;
				this.utoolsData = null;
				await this.init();
				await this.getNavbarTitle();
				await this.getBalloutHistory();
				setTimeout(() => {
					this.showLoaded = false;
				}, 400);
			}
		},

		methods: {
			/**
			 * 查询分享数据
			 * @param {Object} option
			 */
			async getPageShareData(option) {
				try {
					let shareCode = "";
					if (option) shareCode = option.utid ? option.uttype: '';
					const res = await this.$commonFunction.getShareinfoByCode(shareCode);
					this.shareImage = res.shareImage;
					this.shareTitle = res.shareTitle;
					this.pagePath = res.pagePath; //  当前页面路由
					this.pageQuery = res.pageQuery; //  当前页面url参数
				} catch (e) {
				}
			},

			onShareAppMessage(res) {
				let that = this;
				if (res.from === "button") {} else {
					this.$EFSTracking.trackingAction("SHARE_CARD", res.from, {});
				}
				let imageUrl = this.shareImage;
				let path = this.pageQuery ?
					`/${this.pagePath}?${this.pageQuery}` :
					`/${this.pagePath}`;
				let title = this.shareTitle;
				this.$commonSensors.sensorsPageShare();
				this.$sr.setContext({ share_title: this.shareTitle || 'THE MACALLAN EBOUTIQUE麦卡伦' });
				return this.$commonFunction.commonShare(
					res,
					this.shareTitle,
					path,
					this.shareImage
				);
			},
			onShareTimeline() {
				this.$sr.setContext({ share_title: this.shareTitle || 'THE MACALLAN EBOUTIQUE麦卡伦' });
				return {
					title: this.shareTitle ?
						this.shareTitle :
						uni.getStorageSync("storeName") || "THE MACALLAN EBOUTIQUE麦卡伦",
					query: this.pageQuery,
					imageUrl: this.shareImage,
				};
			},

			//  查询用户订单数据给 抽签购使用
			async getOrder() {
				try {
					let customerInfo =
						uni.getStorageSync(CUSTOMER_INFO) || getApp().globalData.customerInfo;
					let merchantInfo =
						uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
					let that = this;
					const parmas = {
						customer_id: customerInfo.customerId,
						merchant_id: merchantInfo.cloudMerchantId,
						page_no: 1,
						page_size: 100,
						store_id: merchantInfo.cloudMerchantStoreId,
					};
					let json = await api.getMyOrderList({
						header: {
							jwt: customerInfo.jwt,
						},
						query: parmas,
					});

					return json?.data?.data?.content || [];
				} catch (e) {
					return [];
				}
			},
			stopClick() {
				return false;
			},
			setTopBar(dealObj) {},
			getNavbarTitle() {
				this.isShowData = false;
				const _showLists = getApp().globalData.plpballoutBannerShowList;
				const z_list = JSON.parse(JSON.stringify(this.navWinAPrizeList));
				const b_lists = [];
				const itemIdList = [];
				let nowTime = new Date().getTime();
				if (z_list.length) {
					z_list.forEach((_el) => {
						const _drawInfo = _el?.drawInfo || null;
						const el_data = this.utoolsClassGoodsLists.find(
							(it) => it.itemId == _el.itemId
						);
						if (el_data && el_data.subtitle) _el.subtitle = el_data.subtitle;
						const asObj =
							_drawInfo.activityInfo &&
							_drawInfo.activityInfo.activitySelectionRecord ?
							_drawInfo.activityInfo.activitySelectionRecord :
							null;
						if (asObj && _drawInfo.activitySwitch) {
							if (
								nowTime >= _drawInfo.exTime.exStartTime &&
								nowTime < _drawInfo.exTime.activityStopTime
							) {
								if ([3, 4, 5].includes(asObj.activitySelectionRecordStatus)) {
									b_lists.push(_el);
									itemIdList.push(_el.itemId);
								}
							}
						}
					});
				}
				// 中奖商品横幅显示
				for (let i = 0; i < itemIdList.length; i++) {
					const _el = itemIdList[i];
					if (!_showLists.includes(_el)) {
						this.isShowData = true;
						getApp().globalData.plpballoutBannerShowList.push(_el);
					}
				}
				if (this.isShowData) this.b_lists = b_lists;
			},
			getNavTitle() {
				let text = "";
				if (this.b_lists.length) {
					if (this.b_lists.length > 1) {
						text = `等${this.b_lists.length}件`;
					}
					const goodsName = this.b_lists[0].subtitle;
					return goodsName + text;
				} else {
					return "";
				}
			},
			countNavHeight() {
				let systemInfo = uni.getSystemInfoSync();
				let rect = uni.getMenuButtonBoundingClientRect ?
					uni.getMenuButtonBoundingClientRect() :
					null; //胶囊按钮位置信息
				// const tabsH = this.utoolsData.children[0].title.style.height
				// const heightTab = tabsH * uni.getSystemInfoSync().windowWidth / 750
				this.navBarHeight = (function() {
					//导航栏高度
					let gap = rect.top - systemInfo.statusBarHeight; //动态计算每台手机状态栏到胶囊按钮间距
					return 2 * gap + rect.height;
				})();
			},
			toID(opt) {
				const {
					id
				} = opt;
				const itemId = id;
				if (!itemId) return;
				const thisData = this.ballotGoodsLists.find((i) => itemId == i.itemId);
				// 根据时间戳跳转itemId
				if (thisData && thisData.drawInfo) {
					wx.pageScrollTo({
						selector: `#utools-parse >>> .${"to" + itemId}`,
						offsetTop: -this.navBarHeight - 52, //计算导航栏的高度
						duration: 800,
						complete: () => {},
						fail: () => {},
						success: () => {},
					});
				}
			},
			async getBalloutHistory() {
				const nowTime = await this.$commonFunction.getServerTime();
				let merchantInfo =
					uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
				const res = await api.recordList({
					method: "GET",
					header: {
						jwt: customerInfo.jwt,
					},
					query: {
						page_no: 1,
						page_size: 4,
					},
				});
				let list = [];
				if (res.code == 1000) {
					list = res.data.content;
					this.historyTotal = res.data.total;
					this.historyList = [];
					for(let j=0;j<list.length;j++){
						const el = list[j];
						el.createTime = this.setDateTime(el.activitySelectionStartTime);
						const formattedDateString = el.activityStopTime.replace(/-/g, '/');
						const goodsOverTime = new Date(formattedDateString).getTime();
						if (el.status == "已订阅提醒") {
							el.title = "已订阅提醒";
							el.btnText = "已设置开售提醒";
							el.titleColor = "#CB171A";
							el.btnTextColor = "#757575";
						} else if (el.status == "已登记") {
							el.title = "已登记";
							el.btnText = "等待公布结果";
							el.titleColor = "#CB171A";
							el.btnTextColor = "#757575";
						} else if (el.status == "登记结束") {
							el.title = "登记结束";
							el.btnText = "等待公布结果";
							el.titleColor = "#757575";
							el.btnTextColor = "#757575";
						} else if (el.status == "恭喜中签") {
							if (goodsOverTime < nowTime) {
								el.title = "恭喜中签";
								el.btnText = "立即购买";
								el.titleColor = "#CB171A";
								el.btnTextColor = "#000000";
							} else {
								el.title = "恭喜中签";
								el.btnText = "查看详情";
								el.titleColor = "#CB171A";
								el.btnTextColor = "#000000";
							}
						} else if (el.status == "待支付") {
							el.title = "恭喜中签";
							el.btnText = "待支付";
							el.titleColor = "#CB171A";
							el.btnTextColor = "#000000";
						} else if (el.status == "已支付") {
							el.title = "恭喜中签";
							el.btnText = "查看订单";
							el.titleColor = "#CB171A";
							el.btnTextColor = "#757575";
						} else if (el.status == "未中签") {
							el.title = "公布结果";
							el.btnText = "未中签";
							el.titleColor = "#757575";
							el.btnTextColor = "#757575";
						} else if (
							el.status == "已取消" ||
							el.status == "已退款" ||
							el.status == "已关闭" ||
							el.status == "交易完成"
						) {
							el.title = "恭喜中签";
							el.btnText = "查看订单";
							el.titleColor = "#CB171A";
							el.btnTextColor = "#000000";
						} else if (el.status == "交易完成") {
							el.title = "恭喜中签";
							el.btnText = "查看订单";
							el.titleColor = "#CB171A";
							el.btnTextColor = "#000000";
						} else if (el.status == "活动结束") {
							el.title = "活动结束";
							el.btnText = "查看详情";
							el.titleColor = "#757575";
							el.btnTextColor = "#000000";
						} else {
							el.title = "";
							el.btnText = "";
							el.titleColor = "";
							el.btnTextColor = "";
						}
						
						this.utoolsClassGoodsLists.forEach((t, tdx) => {
							if (el.itemId == t.itemId) {
								el.subtitle = t.subtitle;
							}
						});
						//  查询商品高清大图
						const _goodsRes = await this.getDetailsById(merchantInfo, el.itemId);
						if (_goodsRes.img) {
							el.frontUrl = _goodsRes.img;
						}
					}
					this.historyList = list;
				}
			},
			setDateTime(dateString) {
			 // 将 "yyyy-MM-dd HH:mm:ss" 转换为 "yyyy/MM/dd HH:mm:ss"
		    	const formattedDateString = dateString.replace(/-/g, '/');
				const date = new Date(formattedDateString);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以加1，并且格式化为两位数
				const day = String(date.getDate()).padStart(2, "0"); // 格式化为两位数

				return `${year}年${month}月${day}日`;
			},
			async getDrawInfo(goodsId, valueId) {
				let customerInfo =
					uni.getStorageSync(CUSTOMER_INFO) || getApp().globalData.customerInfo;
				let merchantInfo =
					uni.getStorageSync(MERCHANT_INFO) || getApp().globalData.merchantInfo;
				let json = await api.getDrawInfo({
					method: "GET",
					query: {
						store_id: merchantInfo.cloudMerchantStoreId,
						merchant_id: merchantInfo.cloudMerchantId,
						customer_id: customerInfo ? customerInfo.customerId : "",
						item_id: goodsId,
						value_id: valueId,
					},
				});
				if (json.code === 1000) {
					return json.data;
				}
			},

			async init() {
				let _utoolsData = await this.getHomeUtoolsData();
				this.utoolsClassGoodsLists = await this.getCateGoods(
					_utoolsData?.classId || 8066
				);
				//  ballot 抽签购商品数据筛选
				if (_utoolsData)
					this.ballotGoodsLists = await this.$commonFunction.buildBallotGoodsData(
						_utoolsData
					);
				this.utoolsData = _utoolsData;
				this.navWinAPrizeList = this.ballotGoodsLists;
			},
			async recordList(jwt) {
				let that = this;
				let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
				const recordListResult = await api.recordList({
					header: {
						jwt: customerInfo.jwt || jwt,
					},
					query: {
						page_no: 1,
						page_size: 100,
					},
				});
				if (recordListResult.code == 1000 && recordListResult.data) {
					that.is_balloutHistory = recordListResult.data.total ? false : true;
					let _listData = recordListResult.data.content;
					let systemInfo = uni.getStorageSync(SYSTEM_INFO);
					let isIos = systemInfo.system.indexOf("iOS");
					let nowTime = new Date().getTime() / 1000;
					for (let i = 0; i < _listData.length; i++) {
						const el = _listData[i];

						let date = el.joinTime;
						let arr = date.split("-");
						let splitDate = arr[0] + "年" + arr[1] + "月" + arr[2];
						let newDate = splitDate.replace(" ", "日 ");
						el.joinTime = newDate;
						if (isIos == 0) {
							el.activityStopTime =
								new Date(el.activityStopTime.replace(/-/g, "/")).getTime() / 1000;
						} else {
							el.activityStopTime =
								new Date(el.activityStopTime).getTime() / 1000;
						}
						if (el.activityStopTime > nowTime) {
							el.classStyle = "black";
						} else {
							el.classStyle = "grey";
						}
						//  查询商品高清大图
						const _goodsRes = await that.getDetailsById(merchantInfo, el.itemId);
						if (_goodsRes.img) el.frontUrl = _goodsRes.img;
						if (_goodsRes.subtitle) el.itemName = _goodsRes.subtitle;
					}
					that.historyList = _listData;
					that.showLoaded = false;

					// that.handleSetTips();
				}
			},
			/**
			 * 获取商品详情
			 * @param {Object} merchantInfo
			 * @param {Object} itemId
			 */
			async getDetailsById(merchantInfo, itemId) {
				return new Promise(async (resolve, reject) => {
					const _res = await api.goodsDetail({
							query: {
								merchant_id: merchantInfo.cloudMerchantId,
								store_id: merchantInfo.cloudMerchantStoreId,
							},
						},
						itemId
					);
					let _img = "";
					let _subtitle = "";
					if (_res && _res.code == 1000 && _res.data) {
						if (_res.data.resources && _res.data.resources.length) {
							const _obj = _res.data.resources.find(
								(item) => item.kind == "hdlp"
							);
							if (_obj && _obj.kind == "hdlp" && _obj.type == "image" && _obj.url)
								_img = _obj.url;
						}
						if (_res.data.frontProperties && _res.data.frontProperties[0]) {
							if (_res.data.frontProperties[0].subtitle)
								_subtitle = _res.data.frontProperties[0].subtitle;
						}
					}
					resolve({
						img: _img,
						subtitle: _subtitle,
					});
				});
			},

			DaytitleFun(timestamp) {
				const date = new Date(timestamp);

				const year = date.getFullYear();
				const month = ("0" + (date.getMonth() + 1)).slice(-2);
				const day = ("0" + date.getDate()).slice(-2);

				return `${month}月${day}日`;
			},
			async getBasicsTag() {
				let tag = await api.getBasicsTag({
					key: "item_status_label",
				});
				let arr = tag?.data?.value ? JSON.parse(tag?.data?.value) : [];
				// arr.sort((a,b)=>  a?.status-b?.status )
				return arr;
			},
			async getHomeUtoolsData() {
				let json = await api.getUtoolsJsonP({
					type: "balloutTimePlpAo",
				});
				return json.success && json?.data ? JSON.parse(json.data) : null;
			},

			// 获取门店商品
			getStoreGoods: async function() {
				return new Promise(async (resolve, reject) => {
					let that = this;
					let merchantInfo = uni.getStorageSync("merchantInfo");
					// 获取门店商品列表
					const json = await api.getStoreGoodsList({
						query: {
							merchantId: merchantInfo.cloudMerchantId,
							page: that.currentPage,
							size: that.pageSize,
						},
					});
					if (json.code === 1000) {
						this.storeProductList = json.data.content;
						// 判断是否显示已加载全部数据
						resolve(json.data.content);
					}
				});
			},
			setHasMore(n) {
				this.hasMore = n;
			},
			/**
			 * 分类商品列表
			 */
			getCateGoods: async function(class_id, is_sort) {
				let that = this;
				let customerInfo = uni.getStorageSync("customerInfo");
				let memberDetails = uni.getStorageSync("memberDetails");
				let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
				let res = await this.$commonFunction.doSearchGoods(
					class_id,
					"",
					1,
					200,
					null,
					"",
					is_sort,
					"",
					"",
					"",
					""
				);
				let cateProductList = res.data.content; // 商品列表
				//sku实时库存查询
				let skuCodeList = [],
					goodsQ = [];
				for (let i = 0; i < cateProductList.length; i++) {
					skuCodeList = skuCodeList.concat(cateProductList[i].skuCodes);
				}
				if (skuCodeList.length) {
					skuCodeList = await this.setSkuCodeList(skuCodeList);
					for (let i = 0; i < skuCodeList.length; i++) {
						let reset = await this.getAvailableBatchQty(
							customerInfo,
							merchantInfo,
							skuCodeList[i]
						);
						goodsQ = reset.length ? goodsQ.concat(reset) : goodsQ;
					}
				}
				// 策略价格
				let listPromises = cateProductList.map(async (item) => {
					item.frontQty = 0;
					if (goodsQ && goodsQ.length) {
						for (let i = 0; i < goodsQ.length; i++) {
							if (
								item.skuCodes.indexOf(goodsQ[i].skuCode) !== -1 &&
								goodsQ[i].availableQty > 0
							) {
								item.frontQty += goodsQ[i].availableQty;
							}
						}
					}
					if (!!item.strategies) {
						let res = await this.$commonFunction.priceRulesDeal(
							item.strategies,
							item.itemmCode
						);
						if (res.price !== 0 && item.itemCode == res.itemCode) {
							item.price = res.price;
						}
						if (res.rulesArr.length > 0 && item.itemCode == res.itemCode) {
							item.rulesArr = res.rulesArr;
						}
					}
					return item;
				});

				let list = await Promise.all(listPromises);
				return list;
			},
			async setSkuCodeList(skuCodeList) {
				if (skuCodeList.length < 21) {
					return [skuCodeList];
				} else {
					const result = skuCodeList.flatMap((value, index, array) => {
						if (index % 20 === 0) {
							return [array.slice(index, index + 20)];
						}
						return [];
					});
					return result;
				}
			},
			async getAvailableBatchQty(customerInfo, merchantInfo, skuCodeList) {
				let reset = await api.getAvailableBatchQty({
						method: "POST",
						header: {
							jwt: customerInfo.jwt,
							"content-type": "application/json",
						},
						// query: JSON.stringify(skuCodeList)
						query: skuCodeList,
					},
					merchantInfo.cloudMerchantId
				);
				if (reset.msg == "SUCCESS" && reset?.data?.length) {
					return reset.data.filter((item) => item.availableQty > 0);
				} else {
					return [];
				}
			},
			onAddCart(e) {
				const {
					data
				} = e.detail;
				this.goods = data;
				this.addCart(e);
			},
			onTriggerComponent(option) {
				const {
					itemId,
					type,
					trackData = null,
					item,
					msg
				} = option.detail.data;
				// 活动细则弹窗
				if (type == "anchorsClick" && JSON.parse(itemId).type == "eventDetails") {
					this.isActivityRule = true;
				}
				if(type === 'showToast' && msg){
					this.handleShowTextToast(msg);
				}else{
					this.$commonUtoolsTrack.onTriggerComponent(option);
				}
			},
			
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			 handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
			srTracking(item, type) {
				try {
					let merchantInfo = uni.getStorageSync("merchantInfo");
					let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
					let userInfo = uni.getStorageSync(USER_INFO);
					const _openOuterItemId = wx.getStorageSync("openOuterItemId");
					const _youshuOpencc = wx.getStorageSync("youshuOpencc");
					if (type == "itemClick") {
						const spuid = !!_openOuterItemId ? item.outerItemId : !!_youshuOpencc ? item.frontProperties[0].frontCode?.toString() : item.itemCode?.toString();
						const spuname = !!_youshuOpencc ? item.itemName + item.frontProperties?.[0].valueName : item.itemName;
						getApp().globalData.$sr.track("trigger_sku_component", {
							sku: {
								sku_id: item.skuCodes[0]?.toString(),
								sku_name: item.itemName,
							},
							spu: {
								spu_id: spuid || item.skuCodes[0]?.toString(),
								spu_name: spuname || item.itemName, // 若商品无spu_name时，可传sku_name信息
							},
							sku_category: [{
								sku_cat_id: item.categoryId?.toString(),
								sku_cat_name: "11",
								sku_parent_cat_id: "null", // 若已是顶级类目，传"null"
							}, ],
							shipping_shop: {
								shipping_shop_id: merchantInfo.cloudMerchantId + "", // 到家类型对接智慧零售入口必传
								shipping_shop_name: "THE MACALLAN EBOUTIQUE麦卡伦", // 到家类型对接智慧零售入口必传
							},
							// "sale": {
							// 	"original_price": parsefloor(item.price), // 对接智慧零售入口必传
							// 	"current_price": parsefloor(item.markingPrice) // 对接智慧零售入口必传
							// },
							primary_image_url: item.skuImageUrl,
						});
						this.$commonSensors.PLPProductClick(item, "", "");
					} else if (type == "addCartClick") {
						//这里是购物车
						getApp().globalData.$sr.track("add_to_cart", {
							action_type: "append_to_cart",
							sku: {
								sku_id: item.skuCodes[0].toString(),
								sku_name: item.itemName,
							},
							spu: {
								spu_id: !!_openOuterItemId ?
									item.outerItemId :
									!!_youshuOpencc ?
									item.frontProperties[0].frontCode?.toString() :
									item.itemCode?.toString(),
								spu_name: !!_youshuOpencc ?
									item.itemName + item.frontProperties?.[0].valueName :
									item.itemName, // 若商品无spu_name时，可传sku_name信息
							},
							sku_category: [{
								sku_cat_id: item.categoryId?.toString(),
								sku_cat_name: "11",
								sku_parent_cat_id: "null", // 若已是顶级类目，传"null"
							}, ],
							shipping_shop: {
								shipping_shop_id: merchantInfo.cloudMerchantId + "", // 到家类型对接智慧零售入口必传
								shipping_shop_name: "THE MACALLAN EBOUTIQUE麦卡伦", // 到家类型对接智慧零售入口必传
							},
							// "sale": {
							// 	"original_price": parsefloor(item.price), // 对接智慧零售入口必传
							// 	"current_price": parsefloor(item.markingPrice) // 对接智慧零售入口必传
							// },
							sku_num: 1,
							primary_image_url: item.skuImageUrl,
						});
						this.$commonSensors.addToCartMF(item, 1, ["常规"]);
					}
				} catch (e) {
					console.log("home-srTracking-error:", e);
				}
			},
			/**
			 * CMS配置页面 转发背景图
			 */
			getCMSPageInfo: async function(identifier, merchantId) {
				let that = this;
				let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
				let mt = "1.0";
				const json = await api.getConfigDetail({
					method: "POST",
					query: {
						identifier: identifier,
						merchantId: merchantId || merchantInfo.cloudMerchantId,
						storeId: merchantInfo.cloudMerchantStoreId,
						mt: mt,
					},
				});
				if (json.data.code === 1000 && json.data.data !== null) {
					let configData = json.data.data;
					let cmsConfigData = {};
					if (this.preview) {
						cmsConfigData = JSON.parse(configData.preview);
					} else {
						cmsConfigData = JSON.parse(configData.content);
						let contents = configData.contents;
						for (let index in contents) {
							let startTime = contents[index].startTime;
							startTime = startTime.substring(0, 19);
							startTime = startTime.replace(/-/g, "/");
							let startTimeTimestamp = new Date(startTime).getTime();
							if (startTimeTimestamp <= new Date().getTime()) {
								cmsConfigData = JSON.parse(contents[index].content);
								break;
							}
						}
					}
					let CMSItembanner = cmsConfigData,
						CMSItembannerImage = cmsConfigData[0];
					that.shareImage = CMSItembannerImage[0].data.child[0].src || "";
					that.shareTitle = CMSItembannerImage[0].data.child[1] ?
						CMSItembannerImage[0].data.child[1].text :
						"";
				}
			},
			ontoHistory() {
				uni.navigateTo({
					url: "/pages/customer/recordList",
				});
			},
		},
	};
</script>

<style lang="less" scoped>
	page {
		// background-color: #fff;
	}

	/* banner */
	.bannerBox {
		margin: 15rpx 15rpx 0;
		background-color: #f9f9f9;
	}

	/* 列表 */
	.goodsList {
		position: relative;
	}

	.has-more {
		font-size: 12px;
		color: #c6c6c6;
		background: #fff;
		width: 100%;
		height: 104rpx;
		text-align: center;
		line-height: 104rpx;
	}

	.ell {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.trans {
		opacity: 0;
	}

	.balloutTime {
		.history-content {
			padding: 0 40rpx;
			margin: 80rpx 0 40rpx 0;
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.title__bar {
			// position: absolute;
			display: flex;
			justify-content: space-between;
			padding: 0 40rpx;
			align-items: center;
			background-color: #a21215;
			height: 88rpx;
		}

		.item-title {
			font-weight: 500;
			font-size: 36rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	.mask-box-2 {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 99;
		background-color: rgba(0, 0, 0, 0.8);
	}

	.params-padding-box-3 {
		overflow: hidden;
		background: #ffffff;
		position: absolute;
		left: 48rpx;
		bottom: 414rpx;
		width: 654rpx;
		height: 796rpx;
	}
</style>